package com.GraduationDesign.backend.utils;

import com.GraduationDesign.backend.po.Project;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;


/**
 * @author DestinyCc
 * @date 2022/5/16
 */
@Component
@Slf4j
public class RequestUtil implements CommandLineRunner {
    @Value("${openapi.token}")
    public String ACCESS_TOKEN;

    public static String TOKEN;

    public static ResponseEntity<String> post(String url, HttpEntity entity){
        log.info("token={}", TOKEN);
        UriComponentsBuilder uri = UriComponentsBuilder.fromUriString(url);
        uri.queryParam("access_token", TOKEN);
        RestTemplate restTemplate = SpringUtils.getBean(RestTemplate.class);
        return restTemplate.postForEntity(uri.toUriString(), entity, String.class);
    }

    public static ResponseEntity<String> getPRList(String requestUrl, String githubUrl){
        log.info("token={}", TOKEN);
        UriComponentsBuilder uri = UriComponentsBuilder.fromUriString(requestUrl);
        uri.queryParam("url", githubUrl)
                .queryParam("access_token", TOKEN);
        RestTemplate restTemplate = SpringUtils.getBean(RestTemplate.class);
        return restTemplate.getForEntity(uri.toUriString(), String.class);
    }

    public static ResponseEntity<String> getDiffFiles(String requestUrl, Project project, String pullNumber, String filename){
        String repo = project.getRepositoryName();
        UriComponentsBuilder uri = UriComponentsBuilder.fromUriString(requestUrl);
        uri.queryParam("repo", repo).queryParam("pullNumber", pullNumber)
                .queryParam("filename", filename).queryParam("access_token", TOKEN);
        RestTemplate restTemplate = SpringUtils.getBean(RestTemplate.class);
        log.info("url={}", uri.toUriString());
        return restTemplate.getForEntity(uri.toUriString(), String.class);
    }
    @Override
    public void run(String... args) throws Exception {
        TOKEN = ACCESS_TOKEN;
    }
}
